using GamFi.Admin.API.Application.Exceptions;
using GamFi.Admin.API.Application.Interfaces;
using GamFi.Admin.API.Application.Resources;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace GamFi.Admin.API.Application.Features.Queries.Image.DeleteImage;

public class DeleteImageCommandHandler(
    IDbContext dbContext,
    IS3Service s3Service,
    IStringLocalizer<ExceptionMessages> localizer)
    : IRequestHandler<DeleteImageCommand, Unit>
{
    /// <inheritdoc/>
    public async Task<Unit> Handle(DeleteImageCommand request, CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);

        var image = await dbContext.Images.FirstOrDefaultAsync(i => i.Id == request.ImageId, cancellationToken);

        if (image is null)
            throw new ImageException(localizer[nameof(ImageException.ImageByIdNotFound)]);

        await s3Service.DeleteAsync(image.Address, cancellationToken: cancellationToken);
        dbContext.Images.Remove(image);
        await dbContext.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}